<template>
  <el-dialog v-model="open" :title="networkTitle" width="70%" :before-close="handleClose">
    <div>
      <!--版本列表-->
      <el-table v-loading="loading" border :data="dataList">
        <el-table-column label="数据源名称" align="center" prop="datasource" width="250"/>
        <el-table-column label="数据集名称" align="center" prop="dataset" width="250"/>
        <el-table-column label="流向字段名称" align="center" prop="directionField" width="150"/>
        <el-table-column label="上传时间" align="center" prop="createTime" width="200"/>
        <el-table-column label="上传人" align="center" prop="createUserName" width="100"/>
        <el-table-column label="备注" align="center" prop="remark" width="150"/>
        <el-table-column :label="networkParams.selectVersionName1" align="center" prop="selectVersion1" width="150"/>
        <el-table-column :label="networkParams.selectVersionName2" align="center" prop="selectVersion2" width="150"/>
        <el-table-column :label="networkParams.selectVersionName3" align="center" prop="selectVersion3" width="150"/>
        <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleDownloadsById(scope.row)">下载</el-button>
            <el-button type="text" @click="handleDeleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--上传工作空间-->
      <el-dialog title="导入网络拓扑数据" v-model="openDialog" width="800px" top="200px" append-to-body
                 :close-on-click-modal="false">
        <el-form ref="uploadRef" label-width="120px" :model="form" :rules="rules">
          <el-form-item label="超图工作空间" prop="attachIds">
            <FileUpload :action="uploadFileUrl" :limit="2" ref="fileUpload" v-model="form.fileList" :fileSize="500"
                        :fileType='["udbx", "smwu"]'/>
          </el-form-item>
          <el-form-item label="数据源名称" prop="datasource">
            <el-input v-model="form.datasource" placeholder="请输入数据源名称" clearable/>
          </el-form-item>
          <el-form-item label="网络数据集名称" prop="dataset">
            <el-input v-model="form.dataset" placeholder="请输入网络数据集名称" clearable/>
          </el-form-item>
          <el-form-item label="流向字段名称" prop="dataset">
            <el-input v-model="form.directionField" placeholder="请输入流向字段名称" clearable/>
          </el-form-item>
          <el-form-item label="">
            <el-link @click="handleDownloadHelp">
              <span style="color:red">（怎样获得工作空间文件、数据源名称、数据集名称和流向字段名称？）</span>
            </el-link>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="5" clearable/>
          </el-form-item>
          <el-form-item label="注意事项：">
            <el-row>
              1、仅支持超图桌面端软件生成的工作空间文件；
            </el-row>
            <el-row>
              2、数据源名称、网络数据集名称要与工作空间文件中的名称保持一致。
            </el-row>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="fileSubmitForm">确 定</el-button>
            <el-button @click="openDialog = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="downloadSelectVersionShp">导出破坏等级分析Shp文件</el-button>
        <el-button type="primary" @click="handleUpload">导入网络拓扑数据</el-button>
        <el-button type="primary" @click="handleCount">计算功能失效等级</el-button>
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="networkdataset">
import FileUpload from "./FileUpload/index.vue"
import {
  getNetworkVersionList,
  newWorkspaceNetworkVersion,
  deleteNetworkanalystVersion,
  countNetworkanalyst
} from "@/api/lifelineProject/networkdataset.js"

const {proxy} = getCurrentInstance();
const props = defineProps(['networkTitle', 'networkParams']);
const emits = defineEmits(['closeDialog', 'completeCount'])
const uploadFileUrl = ref(
    import.meta.env.VITE_APP_BASE_API + "/attachment/uploadSmwuFile"
); // 上传的文件服务器地址
const dataList = ref([]);
const loading = ref(false);
const ids = ref([]);
const openDialog = ref(false);
const open = ref(true);

function handleClose() {
  open.value = false
  emits('closeDialog', true);
}

const data = reactive({
  queryParams: {
    page: 1,
    rows: 10,
    version: '',
    dataType: '',
    taskId: ''
  },
  form: {
    fileList: [],
    datasource: '',
    dataset: '',
    attachIds: '',
    directionField: '',//流向字段名称
    taskId: '',//任务ID
    dataType: '',//类型：供水系统、供气系统、供电系统、交通系统、通信系统
    selectVersion1: '',//所选数据1版本号
    selectVersion2: '',//所选数据2版本号
    selectVersion3: '',//所选数据3版本号
    remark: '',//备注
  },
  rules: {
    datasource: [{required: true, message: "数据源不能为空", trigger: "blur"}],
    dataset: [{required: true, message: "网络数据集不能为空", trigger: "blur"}],
    directionField: [{required: true, message: "流向字段名称不能为空", trigger: "blur"}],
    attachIds: [{required: true, message: "应上传1个.smwu文件和1个.udbx文件", trigger: "blur"}],
  }
});
const {queryParams, form, rules} = toRefs(data);

/** 查询数据列表 */
function getList() {
  loading.value = true;
  queryParams.value.dataType = props.networkParams.dataType;
  queryParams.value.taskId = props.networkParams.taskId;
  getNetworkVersionList(queryParams.value).then(response => {
    dataList.value = response.data.rows ? response.data.rows : [];
    loading.value = false;
  });
}

// 上传
function handleUpload() {
  form.value = {
    fileList: [],
    datasource: '',
    dataset: '',
    attachIds: '',
    directionField: '',//流向字段名称
    taskId: props.networkParams.taskId,//任务ID
    dataType: props.networkParams.dataType,//类型：供水系统、供气系统、供电系统、交通系统、通信系统
    selectVersion1: props.networkParams.selectVersion1,//所选数据1版本号
    selectVersion2: props.networkParams.selectVersion2,//所选数据2版本号
    selectVersion3: props.networkParams.selectVersion3,//所选数据3版本号
    remark: ''
  };
  console.log(form.value);
  proxy.resetForm("uploadRef");
  if (form.value.selectVersion1 == "" && form.value.selectVersion2 == "") {
    proxy.$modal.alertWarning("请先选择数据源并进行破坏等级分析！");
  } else {
    openDialog.value = true;
  }
}

//保存工作空间文件发布服务
function fileSubmitForm() {
  const fileList = JSON.parse(
      JSON.stringify(proxy.$refs["fileUpload"].fileList)
  );
  console.log(fileList);
  let smwuCount = 0;
  let udbxCount = 0;
  let attachIdsArr = [];
  for (let i = 0; i < fileList.length; i++) {
    attachIdsArr.push(fileList[i].attachId);
    if (fileList[i].name.endsWith(".smwu")) {
      smwuCount++;
    } else if (fileList[i].name.endsWith(".udbx")) {
      udbxCount++;
    }
  }
  if (smwuCount == 1 && udbxCount == 1 && fileList.length == 2) {
    //成功上传1个.smwu文件和1个.udbx文件
    form.value.attachIds = attachIdsArr.join(",");
  } else {//清空
    form.value.attachIds = "";
  }
  console.log(form.value);
  proxy.$refs["uploadRef"].validate(valid => {
    if (valid) {
      proxy.$modal.confirm('是否确认上传超图工作空间并发布网络分析服务？').then(function () {
        proxy.$modal.loading("正在发布，请稍候!");
        return newWorkspaceNetworkVersion(form.value);
      }).then(() => {
        proxy.$modal.closeLoading();
        proxy.$modal.alertSuccess("发布成功");
        form.value.fileList = [];
        openDialog.value = false;
        //查询数据列表
        getList();
      }).catch(() => {
        proxy.$modal.closeLoading();
        proxy.$modal.alertError("发布失败");
      });
    }
  });
}

//下载
function handleDownloadsById(row) {
  let id = row.id;
  //下载文件
  let fileName = "超图工作空间数据编号" + row.version + ".zip";
  proxy.download("/hypergraph/downloadNetworkFileZip", {id: id}, fileName);
}

//删除
function handleDeleteById(id) {
  proxy.$modal.confirm("是否确认删除此数据？", 'Warning',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(function () {
    proxy.$modal.loading("正在删除，请稍候!");
    return deleteNetworkanalystVersion({idsStr: id});
  }).then(() => {
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("删除成功");
    //查询数据列表
    getList();
  }).catch(() => {
    proxy.$modal.closeLoading();
    proxy.$modal.alertError("删除失败");
  });
}

//下载帮助文档
function handleDownloadHelp() {
  importTemplate("设施点线数据拓扑构网方法.pdf");
}

// 模板下载
function importTemplate(name) {
  proxy.download("/base/product/downloadExcel", {
    fileName: name
  }, name);
}

//根据sql导出shp文件并下载zip
function downloadShpFileBySql(name, dataset, sqlFilter) {
  console.log(dataset + "根据sql导出shp文件并下载zip---" + sqlFilter);
  //下载文件
  let fileName = name + ".zip";
  proxy.download("/hypergraph/downloadShpFileBySql", {
    dataset: dataset, sqlFilter: sqlFilter
  }, fileName);
}

//下载所选数据源shp文件
function downloadSelectVersionShp() {
  let taskId = props.networkParams.taskId;//任务ID
  let dataType = props.networkParams.dataType;//类型：供水系统、供气系统、供电系统、交通系统、通信系统
  let selectVersion1 = props.networkParams.selectVersion1;//所选数据1版本号
  if (selectVersion1) {
    let selectVersionName1 = props.networkParams.selectVersionName1;//所选数据1名称
    let selectVersionType1 = props.networkParams.selectVersionType1;//所选数据1类型
    let sqlFilter = "task_id='" + taskId + "' and del_flag='0' and type='" + selectVersionType1 + "'";//版本号
    let fileName = selectVersionName1 + "版本" + selectVersion1;
    if (selectVersionName1 == "地下管网" || selectVersionName1 == "供气管网" || selectVersionName1 == "电缆线路") {
      //根据sql导出shp文件并下载zip
      downloadShpFileBySql(fileName, "fxqh_smx_evaluation_results_line", sqlFilter);
    } else {
      //根据sql导出shp文件并下载zip
      downloadShpFileBySql(fileName, "fxqh_smx_evaluation_results", sqlFilter);
    }
  }
  //增加延时，防止下载重名
  setTimeout(function () {
    let selectVersion2 = props.networkParams.selectVersion2;//所选数据2版本号
    if (selectVersion2) {
      let selectVersionName2 = props.networkParams.selectVersionName2;//所选数据2名称
      let selectVersionType2 = props.networkParams.selectVersionType2;//所选数据2类型
      let sqlFilter = "task_id='" + taskId + "' and del_flag='0' and type='" + selectVersionType2 + "'";//版本号
      let fileName = selectVersionName2 + "版本" + selectVersion2;
      //根据sql导出shp文件并下载zip
      downloadShpFileBySql(fileName, "fxqh_smx_evaluation_results", sqlFilter);
    }
  }, 500);
  //增加延时，防止下载重名
  setTimeout(function () {
    let selectVersion3 = props.networkParams.selectVersion3;//所选数据3版本号
    if (selectVersion3) {
      let selectVersionName3 = props.networkParams.selectVersionName3;//所选数据3名称
      let selectVersionType3 = props.networkParams.selectVersionType3;//所选数据3类型
      let sqlFilter = "task_id='" + taskId + "' and del_flag='0' and type='" + selectVersionType3 + "'";//版本号
      let fileName = selectVersionName3 + "版本" + selectVersion3;
      //根据sql导出shp文件并下载zip
      downloadShpFileBySql(fileName, "fxqh_smx_evaluation_results", sqlFilter);
    }
  }, 1000);
}

//计算功能失效等级
function handleCount() {
  let list = dataList.value;
  if (list != null && list.length > 0) {
    let bool = true;
    //判断是否数据版本相同
    let selectVersion1 = props.networkParams.selectVersion1;//所选数据1版本号
    let selectVersion2 = props.networkParams.selectVersion2;//所选数据2版本号
    if (list[0].selectVersion1 != selectVersion1) {
      bool = false;
    }
    if (list[0].selectVersion2 != selectVersion2) {
      bool = false;
    }
    if (props.networkParams.dataType == '供水系统' || props.networkParams.dataType == '供气系统' || props.networkParams.dataType == '供电系统') {
      let selectVersion3 = props.networkParams.selectVersion3;//所选数据3版本号
      if (list[0].selectVersion3 != selectVersion3) {
        bool = false;
      }
    }
    if (bool == false) {
      proxy.$modal.msgWarning("网络拓扑数据与当前破坏等级分析的数据源版本号不一致，请重新导入网络拓扑数据！");
      return;
    }
    proxy.$modal.confirm('是否确定根据网络拓扑数据计算功能失效等级？').then(function () {
      proxy.$modal.loading("正在计算，请稍候!");
      return countNetworkanalyst(list[0]);
    }).then((res) => {
      proxy.$modal.closeLoading();
      if (res.code == 200) {
        proxy.$modal.alertSuccess("计算成功");
        emits('completeCount', true);
        handleClose()
      } else {
        proxy.$modal.alertWarning(res.message);
      }
    }).catch(() => {
      proxy.$modal.closeLoading();
      proxy.$modal.alertError("计算失败");
    });
  } else {
    proxy.$modal.msgWarning("请先导入网络拓扑数据！");
  }
}

//查询数据列表
getList();
</script>

<style lang="scss" scoped>
:deep(.el-link) {
  --el-link-hover-text-color: red;
}
</style>
